package com.djakapm.swing.component.table;

import java.util.Comparator;

@SuppressWarnings("unchecked")
public class SortingDelegateComparator implements Comparator {
	private Comparator comp;
	private boolean isSortAsc;
	
	public SortingDelegateComparator (Comparator c) {
		this.comp = c;
	}
	
	public SortingDelegateComparator (Comparator c, boolean isSortAsc) {
		comp = c;
		this.isSortAsc = isSortAsc;
	}
	
	public int compare (Object o1, Object o2) {
		Object v1 = ((SortingDelegate)o1).value;
		Object v2 = ((SortingDelegate)o2).value;
		if (this.comp != null) {
			if(this.isSortAsc) {
				return comp.compare(v1, v2);
			}
			else {
				return -comp.compare(v1, v2);
			}
		} 
		else 
		if(v1 instanceof Comparable) {return ((Comparable)v1).compareTo(v2);} 
		else {
			String v1Str = String.valueOf(v1);
			String v2Str = String.valueOf(v2);
			return ((Comparable)v1Str).compareTo(v2Str);
		}
	}

}
